import 'package:flutter/material.dart';
import 'package:flutter_novel/config/invoke_manager.dart';

class SimpleRouteObserver extends NavigatorObserver {
  final List<Route> _routes = [];

  /// 获取当前路由栈中的页面数量
  int get pageCount => _routes.length;

  /// 获取路由栈信息
  List<String> get routeNames => _routes.map((route) => route.settings.name ?? '未命名路由').toList();

  @override
  void didPush(Route route, Route? previousRoute) {
    _routes.add(route);
    _printStackInfo('页面入栈');
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    _routes.remove(route);
    _printStackInfo('页面出栈');
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    _routes.remove(route);
    _printStackInfo('页面被移除');
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    if (oldRoute != null) _routes.remove(oldRoute);
    if (newRoute != null) _routes.add(newRoute);
    _printStackInfo('页面替换');
  }

  void _printStackInfo(String action) {
    print('$action - 当前栈中页面数量: $pageCount');
    if (pageCount == 1) {
      InvokeManager.addGestureRecognizer();
    } else {
      InvokeManager.removeGestureRecognizer();
    }
    if (routeNames.isNotEmpty) {
      print('路由栈: ${routeNames.join(" → ")}');
    }
    print('---');
  }

  /// 清空栈（用于测试）
  void clear() {
    _routes.clear();
    print('栈已清空');
  }
}

final SimpleRouteObserver simpleObserver = SimpleRouteObserver();
